package models;

import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

public class DB {
	private static final String ROOT = "files/";
	private static String text;
	private static Path path;
	
	public static void save(String filename) {
		path = Paths.get(ROOT+filename);
		Path file = null;
		try {
			if(Files.exists(path)) {
				Files.delete(path);
			}
			file = Files.createFile(path);
			Files.write(file, text.getBytes());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static List<String> open() {
		List<String> files = new ArrayList<String>();
		Path path = Paths.get(ROOT);
		DirectoryStream<Path> dirStream = null;
		try {
			dirStream = Files.newDirectoryStream(path);
			for (Path p : dirStream) {
				files.add(p.getFileName().toString());
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return files;
	}

	public static String read(String filename) {
		path = Paths.get(ROOT+filename);
		// Open the file logic
		byte[] content = null;
		try {
			content = Files.readAllBytes(path);
		} catch (IOException e) {
			e.printStackTrace();
		}
		DB.text = new String(content);
		return text;
	}
	
	public static String getText() {
		return text;
	}
	public static void setText(String text) {
		DB.text = text;
	}
	
}
